﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Radar.Navigation;

namespace Radar.PathFinding
{
    internal class OpenList
    {

        public AStarNode First;

        public AStarNode GetAndRemoveFirst()
        {
            if (First != null)
            {
                AStarNode result = First;
                First = First.Next;
                return result;
            }
            else
            {
                return null;
            }
        }

        public void Add(AStarNode newNode)
        {
            if (First == null)
            {
                First = newNode;
            }
            else
            {
                AStarNode last = null;
                AStarNode current = First;
                while (current != null && current.F < newNode.F)
                {
                    last = current;
                    current = current.Next;
                }
                if (last == null)
                {
                    First = newNode;
                    newNode.Next = current;
                }
                else
                {
                    last.Next = newNode;
                    newNode.Next = current;
                }
            }
        }

        public bool Contains(AStarNode node)
        {
            AStarNode current = First;
            while (current != null)
            {
                if (current == node) return true;
                current = current.Next;
            }
            return false;
        }

        public void Remove(AStarNode node)
        {
            if (First != null)
            {
                AStarNode last = null;
                AStarNode current = First;
                while (current != null)
                {
                    if (current == node)
                    {
                        if (last == null)
                        {
                            First = node.Next;
                        }
                        else
                        {
                            last.Next = current.Next;
                        }
                        return;
                    }
                    last = current;
                    current = current.Next;
                }
            }
        }

        internal AStarNode GetByWaypoint(Waypoint waypoint)
        {
            AStarNode current = First;
            while (current != null)
            {
                if (current.Waypoint == waypoint) return current;
                current = current.Next;
            }
            return null;
        }
    }
}
